//
//  JMJSortButton.m
//  JinMaJiaDemo
//
//  Created by GripMeMory on 16/1/21.
//  Copyright © 2016年 GripMeMory. All rights reserved.
//

#import "JMJSortButton.h"

#define kSeparateMargin 10 / 2
#define kImageViewWidth 10 / 2

@implementation JMJSortButton

{
    UIButton *_btn;
    UILabel *_label;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        self.userInteractionEnabled = YES;
        
        _btn = [[UIButton alloc] init];
        [_btn setImage:[UIImage imageNamed:@"升序"] forState:UIControlStateNormal];
        [_btn setImage:[UIImage imageNamed:@"降序"] forState:UIControlStateSelected];
        _btn.imageView.contentMode = UIViewContentModeScaleToFill;
        
        _label = [[UILabel alloc] init];
        _label.textAlignment = NSTextAlignmentCenter;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sortedClick)];
        tap.delegate = self;
        [self addGestureRecognizer:tap];
        
        [self addSubview:_label];
        [self addSubview:_btn];
    }
    return self;
}

//- (instancetype)initWithFrame:(CGRect)frame{
//    self = [super initWithFrame:frame];
//    if (self) {
//        
//        self.userInteractionEnabled = YES;
//        
//        _btn = [UIButton buttonWithType:UIButtonTypeCustom];
//        [_btn setImage:[UIImage imageNamed:@"升序"] forState:UIControlStateNormal];
//        [_btn setImage:[UIImage imageNamed:@"降序"] forState:UIControlStateSelected];
//        
//        _label = [[UILabel alloc] init];
//        
//        [self addSubview:_label];
//        [self addSubview:_btn];
//    }
//    return self;
//}

- (void)layoutSubviews{

    _label.frame = CGRectMake(0, 0, self.width - kImageViewWidth - kSeparateMargin, self.height);
    _label.adjustsFontSizeToFitWidth = YES;
    _btn.frame = CGRectMake(_label.right + kSeparateMargin, 0, kImageViewWidth, self.height);
    _label.text = self.title;
    _btn.selected = self.selected;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceivePress:(UIPress *)press{
    
    return YES;
}

- (void)sortedClick{
    self.selected = !self.selected;
    _btn.selected = self.selected;
}

@end
